package com.example.module_hp_white_noise.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;

import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.example.module_hp_white_noise.R;
import com.example.module_hp_white_noise.adapter.HpWhiteNoisePage1Chunk2Adapter;
import com.example.module_hp_white_noise.base.BaseMvvmActivity;
import com.example.module_hp_white_noise.base.BaseUtils;
import com.example.module_hp_white_noise.base.BaseViewModel;
import com.example.module_hp_white_noise.databinding.ActivityHpWhiteNoiseChildListBinding;
import com.example.module_hp_white_noise.entity.HpWhiteNoiseEntity1;
import com.example.module_hp_white_noise.entity.Music;
import com.example.module_hp_white_noise.service.MusicService;
import com.example.module_hp_white_noise.util.Utils;
import com.fwlst.lib_base.utils.AdUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class HpWhiteNoiseChildListActivity extends BaseMvvmActivity<ActivityHpWhiteNoiseChildListBinding, BaseViewModel> {
    private MusicService.MusicServiceBinder serviceBinder;
    private int tags;
    private String title;
    private String imgUrl="";
    private List<HpWhiteNoiseEntity1> mDataList;
    private JSONArray jsonArray;
    private HpWhiteNoisePage1Chunk2Adapter hpWhiteNoisePage1Chunk2Adapter;
    @Override
    protected int initLayout() {
        return R.layout.activity_hp_white_noise_child_list;
    }

    @Override
    protected int initBR() {
        return 0;
    }

    @Override
    protected void initView() {
        //banner广告
        AdUtils.INSTANCE.loadBannerAd(this,binding.bannerContainer);
        BaseUtils.setStatusBar(this,0xFF1E2746);
        try {
            Bundle bd=this.getIntent().getExtras();
            tags = bd.getInt("tags");
            title = bd.getString("title");
            imgUrl = bd.getString("imgUrl");
        }catch (Exception e){
        }
        //返回按钮
        binding.backTb.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();//返回
            }
        });
        hpWhiteNoisePage1Chunk2Adapter = new HpWhiteNoisePage1Chunk2Adapter();
        binding.childListRv.setLayoutManager(new LinearLayoutManager(mContext));
        binding.childListRv.setAdapter(hpWhiteNoisePage1Chunk2Adapter);
        hpWhiteNoisePage1Chunk2Adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bd_item = new Bundle();
                bd_item.putString("songUrl",mDataList.get(position).getMusicUrl());
                bd_item.putString("imgUrl",mDataList.get(position).getImgUrl());
                bd_item.putString("title",mDataList.get(position).getTitle());
                navigateToWithBundle(HpWhiteNoiseChildPlayActivity.class,bd_item);
            }
        });
        initData();
        // 绑定service
        Intent i = new Intent(this, MusicService.class);
        bindService(i, mServiceConnection, BIND_AUTO_CREATE);
    }
    //初始化
    private void initData(){
        List<Integer> sum = BaseUtils.genUniqueRandomVal(3000,10000,1);
        int childImg = mContext.getResources().getIdentifier(imgUrl,"drawable",mContext.getPackageName());
        binding.childNum.setText(sum.get(0)+"人在听");
        binding.childImg.setImageResource(childImg);
        binding.childTitle.setText(title);
        String objString = BaseUtils.getJson("baizaoying.json",mContext);
        try {
            jsonArray = new JSONArray(objString);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        setDataList();
        //随机头像
        ImageView[] tXId={binding.childListTx1,binding.childListTx2,binding.childListTx3,binding.childListTx4,binding.childListTx5};
        List<Integer> tXVal = BaseUtils.genUniqueRandomVal(1,10,5);
        for (int i=0;i<tXId.length;i++){
            int txImgUrl = mContext.getResources().getIdentifier("aa_tx_"+tXVal.get(i),"mipmap",mContext.getPackageName());
            tXId[i].setImageResource(txImgUrl);
        }
    }
    //设置底部list
    private void setDataList(){
        if(jsonArray!=null){
            try {
                int start = (tags-1)*10;
                mDataList = new ArrayList<>();
                for (int i=start;i<start+10;i++){
                    JSONObject jsonObject2 = (JSONObject) jsonArray.get(i);
                    HpWhiteNoiseEntity1 hpWhiteNoiseEntity1 = new HpWhiteNoiseEntity1(i,2,
                            "music_img"+(i%Utils.musicImgCount+1),
                            jsonObject2.getString("ossId"),
                            jsonObject2.getString("name"),
                            "",
                            ""
                    );
                    mDataList.add(hpWhiteNoiseEntity1);
                }
                hpWhiteNoisePage1Chunk2Adapter.setNewData(mDataList);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    // 定义与服务的连接的匿名类
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        // 绑定成功时调用
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

            // 绑定成功后，取得MusicSercice提供的接口
            serviceBinder = (MusicService.MusicServiceBinder) service;

            // 注册监听器
            serviceBinder.registerOnStateChangeListener(listenr);

            Music item = serviceBinder.getCurrentMusic();

            /*if (serviceBinder.isPlaying()){
                // 如果正在播放音乐, 更新控制栏信息
                btnPlayOrPause.setImageResource(R.drawable.zanting);
                playingTitleView.setText(item.title);
                playingArtistView.setText(item.artist);
                if (item.isOnlineMusic){
                    Glide.with(getApplicationContext())
                            .load(item.imgUrl)
                            .placeholder(R.drawable.defult_music_img)
                            .error(R.drawable.defult_music_img)
                            .into(playingImgView);
                }
                else {
                    ContentResolver resolver = getContentResolver();
                    Bitmap img = Utils.getLocalMusicBmp(resolver, item.imgUrl);
                    Glide.with(getApplicationContext())
                            .load(img)
                            .placeholder(R.drawable.defult_music_img)
                            .error(R.drawable.defult_music_img)
                            .into(playingImgView);
                }
            }
            else if (item != null){
                // 当前有可播放音乐但没有播放
                btnPlayOrPause.setImageResource(R.drawable.bofang);
                playingTitleView.setText(item.title);
                playingArtistView.setText(item.artist);
                if (item.isOnlineMusic){
                    Glide.with(getApplicationContext())
                            .load(item.imgUrl)
                            .placeholder(R.drawable.defult_music_img)
                            .error(R.drawable.defult_music_img)
                            .into(playingImgView);
                }
                else {
                    ContentResolver resolver = getContentResolver();
                    Bitmap img = Utils.getLocalMusicBmp(resolver, item.imgUrl);
                    Glide.with(getApplicationContext())
                            .load(img)
                            .placeholder(R.drawable.defult_music_img)
                            .error(R.drawable.defult_music_img)
                            .into(playingImgView);
                }
            }*/
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            // 断开连接时注销监听器
            serviceBinder.unregisterOnStateChangeListener(listenr);
        }
    };

    // 实现监听器监听MusicService的变化，
    private MusicService.OnStateChangeListenr listenr = new MusicService.OnStateChangeListenr() {

        @Override
        public void onPlayProgressChange(long played, long duration) {}

        @Override
        public void onPlay(Music item) {
            // 播放状态变为播放时
            /*btnPlayOrPause.setImageResource(R.drawable.zanting);
            playingTitleView.setText(item.title);
            playingArtistView.setText(item.artist);
            btnPlayOrPause.setEnabled(true);
            if (item.isOnlineMusic){
                Glide.with(getApplicationContext())
                        .load(item.imgUrl)
                        .placeholder(R.drawable.defult_music_img)
                        .error(R.drawable.defult_music_img)
                        .into(playingImgView);
            }
            else {
                ContentResolver resolver = getContentResolver();
                Bitmap img = Utils.getLocalMusicBmp(resolver, item.imgUrl);
                Glide.with(getApplicationContext())
                        .load(img)
                        .placeholder(R.drawable.defult_music_img)
                        .error(R.drawable.defult_music_img)
                        .into(playingImgView);
            }*/
        }

        @Override
        public void onPause() {
            // 播放状态变为暂停时
            /*btnPlayOrPause.setImageResource(R.drawable.bofang);
            btnPlayOrPause.setEnabled(true);*/
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(mServiceConnection);
        AdUtils.INSTANCE.destroyBannerAd();
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}